Python Cheatsheet

PYTHON BASICS

Topic / Command Explanation Example / Usage
Installation Install Python packages. python -m pip install
Interpreter Invoke the Python REPL interactively. python
Script Execution Run a Python script file. python my_script.py
Comments Lines ignored by the interpreter. # This is a comment
print() Display output to stdout. print("Hello World")
Variables Automatically typed; no need for explicit declaration. x = 42
Multiple Assignment Assign multiple variables at once. a, b, c = 1, 2, 3
Type Checking Find the type of a variable. type(x) → <class 'int'>
Type Casting Convert between types (str, int, float, list, etc.). int("100") → 100
String Literals Create strings with single, double, or triple quotes. "Hello", 'Hi', """Multi-line string"""
String Formatting Format strings with f-strings or format method. f"Value is {x}" or "{}".format(x)
String Methods Built-in methods for manipulation (split, lower, replace). "Hello".upper() → "HELLO"
Help / Docstrings Built-in help or docstrings. help(str) or print(str.doc)

CONTROL FLOW (CONDITIONS AND LOOPS)

Topic / Statement Explanation Example / Usage
if, elif, else Conditional statements. if x > 0: ... elif x == 0: ... else: ...
for loop Iterate over a sequence or iterable. for i in range(5): print(i)
while loop Repeat until a condition becomes False. while x < 5: x += 1
break Exit a loop prematurely. if condition: break
continue Skip to next iteration of a loop. if condition: continue
pass Do nothing (placeholder). if condition: pass
range() Generate a sequence of integers. range(0, 10, 2) → 0, 2, 4, 6, 8
else (on loops) Executes if no break occurs in a loop. for i in range(5): ... else: print("Done")

DATA STRUCTURES

Structure / Topic Explanation Example / Usage
List Ordered, mutable collection. my_list = [1, 2, 3]
List Comprehension Compact way to build lists. [x**2 for x in range(5)] → [0,1,4,9,16]
Tuple Ordered, immutable collection. my_tuple = (1, 2, 3)
Set Unordered, unique elements. my_set = {1, 2, 3}
Dict Key-value pairs, mutable. my_dict = {"key": "value"}
Access Dict Values Retrieve or set dictionary values by key. my_dict["key"]
Dict Methods get(), keys(), values(), items(). my_dict.get("key", default_val)
Adding to List Use append() or extend(). my_list.append(4)
Removing from List Use remove(value), pop(index), or del. my_list.remove(2)
Slicing Access sub-portions of sequences. my_list[1:3] → elements at index 1 and 2

FUNCTIONS AND LAMBDA

Topic / Keyword Explanation Example / Usage
def Define a function. def my_func(a, b=0): return a + b
Return Values Functions return data with return statement. return a + b
Positional Arguments Regular arguments in order. my_func(1, 2)
Keyword Arguments Specifying argument name in function call. my_func(a=1, b=2)
args Accept variable number of positional args. def my_func(args):
**kwargs Accept variable number of keyword args. def my_func(**kwargs):
Lambda Functions Anonymous functions. my_lambda = lambda x: x2
Docstrings Document your function. def f(x): """Does X.""" return x
Annotations Type hints. def f(x: int) -> int: return x2

OBJECT-ORIENTED PROGRAMMING (OOP)

Concept / Keyword Explanation Example / Usage
class Defines a new class. class MyClass: ...
init Class constructor/initializer. def init(self, val): self.val = val
self Refers to the instance within class methods. self.val = val in init
Instance Method Functions defined inside a class that operate on instance. def method(self): return self.val
Class Variable Shared across all instances. class MyC: var=0
Inheritance Child class inherits attributes and methods from parent. class Child(Parent): ...
super() Call parent class methods/constructors. super().init()
str / repr String representation of an object. def str(self): return f"val={self.val}"
@staticmethod Method that doesn’t use self (no instance needed). @staticmethod def foo(): return "bar"
@classmethod Method that receives class (cls) as the first argument. @classmethod def from_data(cls, data): ...

ERROR HANDLING AND LOGGING

Concept / Keyword Explanation Example / Usage
try / except Catch exceptions. try: ... except ValueError: ...
else Code block that executes if no exception is raised. try: ... except: ... else: ...
finally Code block that always executes. try: ... finally: cleanup()
raise Raise an exception manually. raise ValueError("Bad value")
Logging with logging Standard logging library. import logging; logging.info("Info msg")
log levels Common levels: DEBUG, INFO, WARNING, ERROR, CRITICAL. logging.warning("Warning message")

FILE HANDLING

Topic / Keyword Explanation Example / Usage
open() Opens a file. f = open("file.txt", "r")
read(), readline() Read entire file or read line-by-line. data = f.read()
write() Write string data to a file. f.write("Hello")
close() Close the file when done. f.close()
with statement Context manager for file handling (auto close). with open("file.txt", "r") as f: data = f.read()
modes Common modes: 'r', 'w', 'a', 'x', 'rb', 'wb'. open("file.bin", "wb")

VIRTUAL ENVIRONMENTS AND MODULES

Concept / Keyword Explanation Example / Usage
Virtualenv Create isolated Python environments. python -m venv venv_name
Activate venv (Linux) Activate virtual environment on Linux/macOS. source venv_name/bin/activate
Activate venv (Windows) Activate virtual environment on Windows. venv_name\Scripts\activate
Deactivate venv Exit out of the virtual environment. deactivate
Modules Individual .py files with reusable code. import my_module
Packages Directories with init.py that group modules. from my_package import my_module
name == "main" Check if file is run as script or imported as module. if name == "main": main()
pip freeze List installed packages with versions. pip freeze > requirements.txt
Requirements file Reproduce environment. pip install -r requirements.txt

CONCURRENCY, PARALLELISM, AND ASYNC

Topic / Package Explanation Example / Usage
threading Concurrency via threads (subject to GIL for CPU-bound code). import threading
multiprocessing True parallelism by spawning processes. from multiprocessing import Process
async / await Asynchronous I/O operations. async def my_coro(): await something()
asyncio Core library for async in Python. import asyncio
GIL (Global Interpreter Only one thread runs Python bytecode at a time. N/A
Lock)

NUMPY CHEATSHEET

Concept / Function Explanation Example / Usage
import numpy as np Conventional alias for NumPy. import numpy as np
Creating Arrays Use np.array() or various np.* methods. arr = np.array([1,2,3])
np.zeros, np.ones Create arrays of zeros or ones. np.zeros((2,2)), np.ones((3,3))
np.arange, np.linspace Generate ranges or evenly spaced numbers. np.arange(0,10,2), np.linspace(0,1,5)
Shape Get or set array shape. arr.shape, arr.reshape(2,3)
Indexing & Slicing Similar to Python lists but for n-dim arrays. arr[0,1], arr[:, 0], arr[1:3, :]
Vectorized Ops Elementwise operations. arr + 2, arr * 3, arr1 + arr2
Broadcasting Automatic expansion to match shapes in operations. arr + scalar, arr + smaller arr
np.sum, np.mean, etc. Aggregations on arrays. np.sum(arr), np.mean(arr, axis=0)
Matrix Multiplication Use the @ operator or np.dot(). arr1 @ arr2, np.dot(arr1, arr2)
Axis Argument Choose dimension for operations. np.sum(arr, axis=0)
np.random Random sampling (rand, randn, randint). np.random.rand(3,2)

PANDAS CHEATSHEET

Concept / Function Explanation Example / Usage
import pandas as pd Conventional alias for pandas. import pandas as pd
pd.Series 1D labeled array. s = pd.Series([1,2,3], name="Numbers")
pd.DataFrame 2D labeled data structure. df = pd.DataFrame(data, columns=[...])
Reading Data Common I/O methods (CSV, Excel, SQL). pd.read_csv("file.csv"), pd.read_excel(...),
pd.read_sql(...)
df.head(), df.tail() Preview top/bottom rows of a DataFrame. df.head()
df.info(), df.describe() Get info and summary statistics. df.info(), df.describe()
Indexing & Slicing .loc (label-based), .iloc (integer-based). df.loc[0], df.iloc[0:3, 1:4]
Filtering Rows Boolean indexing. df[df["col"] > 10]
df["col"] Select a single column as a Series. s = df["col"]
Adding Columns Assign a new column directly. df["new"] = df["a"] + df["b"]
Dropping Remove rows or columns. df.drop("col", axis=1)
Grouping & Aggregation groupby and agg methods. df.groupby("key").agg({"val": "mean"})
Merging/Joining Combine DataFrames on shared columns/index. pd.merge(df1, df2, on="key")
df.apply(), df.applymap() Apply functions to columns/rows or elementwise. df["col"].apply(np.log)
df.pivot, df.pivot_table Reshape data. df.pivot_table(values="val", index="rowKey")
df.sort_values() Sort by one or more columns. df.sort_values("col", ascending=False)

MATPLOTLIB CHEATSHEET

Concept / Function Explanation Example / Usage
import matplotlib.pyplot as plt Main plotting interface. import matplotlib.pyplot as plt
Basic Plot Simple line plot. plt.plot(x, y)
Scatter Plot Plot data as points. plt.scatter(x, y)
Bar Plot Plot bar chart. plt.bar(categories, values)
Histogram Distribution of data. plt.hist(data, bins=20)
Labels & Titles Add axis labels and chart title. plt.xlabel("X"), plt.ylabel("Y"), plt.title("My Plot")
Show Plot Render the figure. plt.show()
Subplots Multiple plots in a figure. plt.subplot(2,1,1); plt.plot(...);
fig, ax = plt.subplots() Object-oriented approach. ax.plot(x, y)
Save Figure Save a figure to file. plt.savefig("plot.png")
Ticks & Legends Adjust ticks or add legend. plt.xticks(...), plt.legend()

SCIKIT-LEARN CHEATSHEET

Concept / Class / Function Explanation Example / Usage
import sklearn Main machine learning library in Python. from sklearn import datasets
Datasets Built-in toy datasets (Iris, Boston, etc.). iris = datasets.load_iris()
Train/Test Split Partition data for training and testing. from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = ...
Estimators (Models) Classes that implement fit(), predict(), transform(). from sklearn.linear_model import LogisticRegression
Model Fitting Train model on data. model = LogisticRegression()
model.fit(X_train, y_train)
Prediction Predict on new or test data. preds = model.predict(X_test)
Evaluation Evaluate with common metrics. from sklearn.metrics import accuracy_score
Transformers (e.g. Scaling) Preprocessing (StandardScaler, MinMaxScaler, etc.). from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train)
Pipelines Chain transformers and estimators. from sklearn.pipeline import Pipeline
pipe = Pipeline([...])
Cross-Validation Evaluate models by splitting in multiple ways. from sklearn.model_selection import cross_val_score